/**
 * Project Name:hr-web
 * File Name:VelocityUtil.java
 * Package Name:com.app.biz.util
 * Date:2016年1月24日下午9:37:13
 * Copyright (c) 2016, chenzhou1025@126.com All Rights Reserved.
 *
*/

package com.app.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.tools.generic.DateTool;

/**
 * ClassName:VelocityUtil <br/>
 * Date: 2016年1月24日 下午9:37:13 <br/>
 * 
 * @author liuliang
 * @version
 * @since JDK 1.6
 * @see
 */
public class VelocityUtil {

    public static String render(HttpServletRequest request, Object data) {
        FileOutputStream fos = null;
        BufferedWriter writer = null;
        String path = "/upload/" + DateUtil.fomart(new Date(), "yyyyMMdd") + "/"
            + UUID.randomUUID().toString().replace("-", "") + ".html";
        String filePath = request.getServletContext().getRealPath(path);
        String tplPath = request.getServletContext().getRealPath("/WEB-INF/views_lietou/tpl/");
        try {
            Properties properties = new Properties();
            // 指定生成静态文档需要的模板文件所在的目录
            properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, tplPath);
            VelocityEngine engine = new VelocityEngine();
            // 初始化模板引擎
            engine.init(properties);
            // 根据API_TEMPLATE_FILE读取生成静态文档需要的模板文件
            Template template = engine.getTemplate("resume.vm", "UTF-8");
            VelocityContext context = new VelocityContext();
            // 将生成文档需要的数据apiModel放入模板引擎的上下文中
            DateTool datetool = new DateTool();
            context.put("data", data);
            context.put("datetool", datetool);
            // 确定静态文档在共享文件目录的完整存储路径
            File file = new File(filePath);

            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(file);
            writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));// 设置写入的文件编码,解决中文问题
            // 将数据与模板merge，并写入到静态文档
            template.merge(context, writer);
        } catch (Exception e) {
            // 打印日志
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // 打印日志
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // 打印日志
                }
            }
        }

        return path;
    }
}
